#include "UdpClient.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include "Common.hpp"
#include <pthread.h>
#include <unistd.h>
#include <signal.h>

int sockfd = -1;
int gweclome = 0;
struct sockaddr_in server;

void ClientQuit(int signo)
{
    (void)signo;
    const std::string quit = "QUIT";
    int n = ::sendto(sockfd, quit.c_str(), quit.size(), 0, CONV(&server), sizeof(server));
    exit(0);
}

void *Recevr(void *args)
{
    while (true)
    {
        char buffer[1024];
        struct sockaddr_in Returnserver;
        socklen_t len = sizeof(Returnserver);

        int n = ::recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, CONV(&Returnserver), &len);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cerr << buffer << std::endl;
        }
    }
}

// Client.udp serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << "serverip serverport" << std::endl;
        exit(USAGE_ERR);
    }

    signal(2, ClientQuit);

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(SOCKET_ERR);
    }

    // 填充server信息

    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = ::inet_addr(serverip.c_str());

    pthread_t tid;
    pthread_create(&tid, nullptr, Recevr, nullptr);

    std::string online = " ...来了哈!";
    int n = ::sendto(sockfd, online.c_str(), online.size(), 0, CONV(&server), sizeof(server));

    while (true)
    {
        // 为了避免多线程同时执行代码，导致缓冲区堵塞
        if (gweclome == 0)
            std::cout << "Weclome To QQ, 请输入用户名# ";

        else if (gweclome != 0)
        {
            sleep(1);
            if (gweclome == 1)
            {
                std::cout << "筑基您好！, 请挑选聊天的用户！# ";
            }
            else
            {
                std::cout << "您是她的好友, 请输入信息！# ";
            }
        }
        // printf("please ...");

        std::string message;
        std::getline(std::cin, message);

        int n = ::sendto(sockfd, message.c_str(), message.size(), 0, CONV(&server), sizeof(server));

        (void)n;
        gweclome++;
    }

    return 0;
}